package com.ucode.springboot.starter.web.validator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeEntityValidatorException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 手动校验工具类
 * @author: liliang
 * @date: 2019年12月19日 下午2:39:19
 */
public class ValidatorUtils {
    
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws UcodeEntityValidatorException 校验不通过，则报UcodeEntityValidatorException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) throws UcodeEntityValidatorException{
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            @SuppressWarnings("unchecked")
            List<ConstraintViolation<Object>> constraints = (List<ConstraintViolation<Object>>) constraintViolations.iterator();
            String message = constraints.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
            String msg = ResultCodeEnum.VALIDATE_FAILED.message+"[%s]";
            throw new UcodeEntityValidatorException(String.format(msg, message));
        }
    }
}